package com.hsqyz.common.utils.sql;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * MySQL连接URL解析工具
 *
 * @author lcz
 */
public class MySQLUrlParserUtils {

    // 定义MySQL连接URL的正则表达式
    private static final String MYSQL_URL_REGEX = "jdbc:mysql://(.*?):(\\d+)/([^?]+)(\\?(.*))?";

    // 解析MySQL连接URL并提取相关信息的方法
    public static MySQLConnectionInfo parse(String url) {
        // 使用正则表达式进行匹配
        Pattern pattern = Pattern.compile(MYSQL_URL_REGEX);
        Matcher matcher = pattern.matcher(url);

        // 如果匹配成功
        if (matcher.find()) {
            // 提取主机名、端口、数据库名称以及参数字符串
            String host = matcher.group(1);
            int port = Integer.parseInt(matcher.group(2));
            String database = matcher.group(3);
            String paramsString = matcher.group(5);

            // 解析参数字符串，提取用户名和密码
            String[] params = paramsString.split("&");
            String username = null;
            String password = null;
            for (String param : params) {
                String[] keyValue = param.split("=");
                if (keyValue.length == 2) {
                    String key = keyValue[0];
                    String value = keyValue[1];
                    if ("user".equalsIgnoreCase(key)) {
                        username = value;
                    } else if ("password".equalsIgnoreCase(key)) {
                        password = value;
                    }
                    // 可以根据需要添加更多的参数解析
                }
            }

            // 返回MySQL连接信息对象
            return new MySQLConnectionInfo(host, port, username, password, database);
        }

        // 如果匹配失败，返回null
        return null;
    }

    // 测试方法
    public static void main(String[] args) {
        // 测试用的MySQL连接URL
        String url = "jdbc:mysql://localhost:3306/mydatabase?user=root&password=123456";
        // 解析URL并获取连接信息对象
        MySQLConnectionInfo connectionInfo = MySQLUrlParserUtils.parse(url);
        // 如果解析成功
        if (connectionInfo != null) {
            // 打印连接信息
            System.out.println("Host: " + connectionInfo.getHost());
            System.out.println("Port: " + connectionInfo.getPort());
            System.out.println("Username: " + connectionInfo.getUsername());
            System.out.println("Password: " + connectionInfo.getPassword());
            System.out.println("Database: " + connectionInfo.getDatabase());
        } else {
            // 打印错误消息
            System.out.println("Invalid MySQL URL");
        }
    }

    // MySQL连接信息类
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MySQLConnectionInfo {
        private String host;
        private Integer port;
        private String username;
        private String password;
        private String database;
    }

}
